package models.roleAndPermessions;

import com.avaje.ebean.Ebean;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.SqlQuery;
import com.avaje.ebean.SqlRow;
import play.db.ebean.Model;
import play.libs.Json;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wkhl on 2016/12/27.
 */
@Entity
@Table(name = "role_permeission")
public class RoleAndPermeission extends Model{
    public static Finder<Integer,RoleAndPermeission> finder =
            new Finder<Integer,RoleAndPermeission>(Integer.class, RoleAndPermeission.class);
    @Id
    public  Integer  id;
    public  Integer   role_id;//角色Id
    public  String   permeission_id;//权限Id


    public static List<String> findPermeissionOfRole(Integer role_id){
        List<String> allParentLeftList =new ArrayList<>();//allParentLeftList集合中的元素是权限id或根节点标识。他们都含有子节点
        List<String> allpermeissionOfRole =new ArrayList<>();//角色对应权限list（包扩含有子节点的节点和不含有子节点的节点）
        List<String> allSonPermeissionOfRole =new ArrayList<>();//此集合包含的元素为allpermeissionOfRole集合去除allParentLeftList集合中元素的集合,即：没有子节点的元素的集合

        EbeanServer ebeanServer = Ebean.getServer("default");
        String sql1 =  "SELECT DISTINCT parent FROM permeissions";
        SqlQuery sqlQuery = ebeanServer.createSqlQuery(sql1);
        List<SqlRow> list =sqlQuery.findList();
        for (int i =0;i<Json.toJson(list).size();i++){
            allParentLeftList.add(Json.toJson(list).get(i).get("parent").asText());
        }

        List<RoleAndPermeission> permeissionOfRole =finder.where().eq("role_id",role_id).findList();
        for (int i=0;i<permeissionOfRole.size();i++){
            String permeission_id =permeissionOfRole.get(i).permeission_id;
            allpermeissionOfRole.add(permeission_id.toString());
        }

         allSonPermeissionOfRole =findDeff(allParentLeftList,allpermeissionOfRole);

        return allSonPermeissionOfRole;
    }

    public static List findDeff(List allParentLeftList,List allpermeissionOfRole){
        List allSonPermeissionOfRole = new ArrayList() ;

        for (int i=0;i<allpermeissionOfRole.size();i++){
            String permeission = (String) allpermeissionOfRole.get(i);
            Boolean ifContains = allParentLeftList.contains(permeission);
            if (!ifContains){//不含有子节点
                allSonPermeissionOfRole.add(permeission);
            }
        }

        return allSonPermeissionOfRole;

    }

}
